package usw.webserver.util;

public final class CastUtil {

	/**
	 * 
	 * @param obj
	 * @return
	 */
	public static String castString(Object obj) 
	{
		return	CastUtil.castString(obj, "");
	}
	
	/**
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static String castString(Object obj, String defaultValue)
	{
		return	obj != null? String.valueOf(obj) : defaultValue;
	}
	
	/**
	 * 
	 * @param obj
	 * @return
	 */
	public static double castDouble(Object obj)
	{
		return	CastUtil.castDouble(obj, 0);
	}
	
	/**
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static double castDouble(Object obj, double defaultValue)
	{
		double  doubleValue = defaultValue;
		
		if	(obj != null)
		{
			String	strValue = castString(obj);
			
			if	(StringUtil.isNotEmpty(strValue))
			{
				try
				{
					doubleValue = Double.parseDouble(strValue);
				}
				catch(NumberFormatException ex)
				{
					doubleValue = defaultValue;
				}
			}
		}
		
		return	doubleValue;
	}
	
	/**
	 * 
	 * @param obj
	 * @return
	 */
	public static long castLong(Object obj)
	{
		return	CastUtil.castLong(obj, 0);
	}
	
	/**
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static long castLong(Object obj, long defaultValue)
	{
		long	longValue = defaultValue;
		
		if	(obj != null)
		{
			String	strValue = castString(obj);
			
			if	(StringUtil.isNotEmpty(strValue))
			{
				try
				{
					longValue = Long.parseLong(strValue);
				}
				catch(NumberFormatException ex)
				{
					longValue = defaultValue;
				}
			}
		}
		
		return	longValue;
	}	
	
	/**
	 * 
	 * @param obj
	 * @return
	 */
	public static int castInt(Object obj)
	{
		return	CastUtil.castInt(obj, 0);
	}
	
	/**
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static int castInt(Object obj, int defaultValue)
	{
		int	intValue = defaultValue;
		
		if	(obj != null)
		{
			String	strValue = castString(obj);
			
			if	(StringUtil.isNotEmpty(strValue))
			{
				try
				{
					intValue = Integer.parseInt(strValue);
				}
				catch(NumberFormatException ex)
				{
					intValue = defaultValue;
				}
			}
		}
		
		return	intValue;
	}
	
	/**
	 * 
	 * @param obj
	 * @return
	 */
	public static boolean castBoolean(Object obj)
	{
		return	CastUtil.castBoolean(obj, false);
	}
	
	/**
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static boolean castBoolean(Object obj, boolean defaultValue)
	{
		boolean	booleanValue = defaultValue;
		
		if	(obj != null) 
		{
			booleanValue = Boolean.parseBoolean(castString(obj));
		}
		
		return	booleanValue;
	}
}
